import React, { useState, useEffect } from "react";
import { post, get } from "../../../components/axios";
import {
  Table,
  Button,
  Input,
  Tag,
  Space,
  Pagination,
  Card,
  Modal,
  Form,
  Select,
  InputNumber,
  message,
  Popconfirm,
  Spin,
  Row,
  Col,
} from "antd";
import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  SearchOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
const { Option } = Select;
const { TextArea } = Input;
import { useNavigate } from "react-router-dom";

// 需求类型选项
const demandTypes = [
  { label: "BUG", value: "BUG" },
  { label: "功能需求", value: "功能需求" },
  { label: "优化需求", value: "优化需求" },
  { label: "性能问题", value: "性能问题" },
  { label: "兼容性问题", value: "兼容性问题" },
];

// 状态选项
const statusOptions = [
  { label: "待处理", value: "待处理" },
  { label: "处理中", value: "处理中" },
  { label: "已完成", value: "已完成" },
  { label: "已关闭", value: "已关闭" },
];

// 优先级选项
const priorityOptions = [
  { label: "高", value: "高" },
  { label: "中", value: "中" },
  { label: "低", value: "低" },
];

export default function AfterSalesDemand() {
  // console.log('AfterSalesDemand 组件渲染');
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [search, setSearch] = useState("");
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(6);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [list, setlist] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const navigate = useNavigate();
  // 获取URL参数中的项目信息
  const urlParams = new URLSearchParams(window.location.search);
  const projectId = urlParams.get('projectId') || 'P123123231';
  const projectName = urlParams.get('projectName') || 'CRM系统';

  // 获取数据（支持分页和多条件搜索）
  const getlist = async (params = {}) => {
    setLoading(true);
    const res = await get('/afterSalesDemand/list', {
      page: params.page || current,
      pageSize: params.pageSize || pageSize,
      ...params.filters // 这里filters里有keyword
    });
    setLoading(false);
    if (res.data.code === 200) {
      setlist(res.data.data.list);
      setTotal(res.data.data.total);
      setCurrent(res.data.data.page);
      setPageSize(res.data.data.pageSize);
    }
  };

  // 初始加载
  useEffect(() => {
    getlist()
  }, []);

  // 搜索
  const handleSearch = async () => {
    const values = searchForm.getFieldsValue();
    getlist({ page: 1, pageSize, filters: values });
  };

  // 重置
  const handleReset = () => {
    searchForm.resetFields();
    getlist({ page: 1, pageSize });
  };

  // 添加记录
  const handleAdd = () => {
    setEditingRecord(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 编辑记录
  const handleEdit = (record) => {
    setEditingRecord(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  // 删除记录
  const handleDelete = async (id) => {
    try {
      const response = await post('/afterSalesDemand/delete', { id });
      if (response.data.code === 200) {
        message.success('删除成功');
        // fetchData(current, pageSize);
        getlist()
      } else {
        message.error(response.data.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的记录');
      return;
    }

    try {
      const response = await post('/afterSalesDemand/batchDelete', {
        ids: selectedRowKeys
      });
      if (response.data.code === 200) {
        message.success(response.data.msg);
        setSelectedRowKeys([]);
        // fetchData(current, pageSize);
      } else {
        message.error(response.data.msg || '批量删除失败');
      }
    } catch (error) {
      console.error('批量删除失败:', error);
      message.error('批量删除失败');
    }
  };

  // 保存记录
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      const saveData = {
        ...values,
        projectId,
        projectNumber: projectId,
        projectName,
        creator: "当前用户", // 这里应该从用户状态获取
      };

      let response;
      if (editingRecord) {
        // 更新
        response = await post('/afterSalesDemand/update', {
          ...saveData,
          id: editingRecord.id
        });
      } else {
        // 新增
        response = await post('/afterSalesDemand/add', saveData);
      }

      if (response.data.code === 200) {
        message.success(editingRecord ? '更新成功' : '添加成功');
        setModalVisible(false);
        getlist()
        // fetchData(current, pageSize);
      } else {
        message.error(response.data.msg || (editingRecord ? '更新失败' : '添加失败'));
      }
    } catch (error) {
      console.error('保存失败:', error);
      message.error('保存失败');
    }
  };

  // 分页
  const handlePageChange = (page, pageSize) => {
    const values = searchForm.getFieldsValue();
    getlist({ page, pageSize, filters: values });
  };

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      align: "center",
      width: 60,
      render:(text,record,index) => index + 1
    },
    {
      title: "售后需求名称",
      dataIndex: "name",
      width: 180,
    },
    {
      title: "需求类型",
      dataIndex: "type",
      width: 100,
      render: (type) => (
        <Tag color={type === 'BUG' ? 'red' : type === '功能需求' ? 'blue' : 'green'}>
          {type}
        </Tag>
      ),
    },
    {
      title: "总计划工时",
      dataIndex: "planHour",
      width: 100,
    },
    {
      title: "需求成本",
      dataIndex: "cost",
      width: 120,
    },
    {
      title: "是否收费",
      dataIndex: "charge",
      width: 100,
      render: (charge) => (
        <Tag color={charge === '是' ? 'green' : 'orange'}>
          {charge}
        </Tag>
      ),
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 100,
      render: (status) => {
        const colorMap = {
          '待处理': 'orange',
          '处理中': 'blue',
          '已完成': 'green',
          '已关闭': 'gray'
        };
        return <Tag color={colorMap[status] || 'default'}>{status}</Tag>;
      },
    },
    {
      title: "备注",
      dataIndex: "remark",
      width: 120,
      ellipsis: true,
    },
    {
      title: "创建人",
      dataIndex: "creator",
      width: 100,
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      width: 120,
    },
    {
      title: "更新时间",
      dataIndex: "updateTime",
      width: 120,
    },
    {
      title: "操作",
      key: "action",
      align: "center",
      width: 160,
      render: (_, record) => (
        <Space size={8}>
          <span
            style={{
              background: "#ffb366",
              color: "#fff",
              borderRadius: 4,
              padding: "2px 8px",
              fontSize: 14,
              display: "inline-block",
              lineHeight: 1.2,
              fontWeight: 500,
            }}
            onClick={() => navigate('/projects/aftersaleslist')}
            
          >
            需求列表
          </span>
          <Button
            size="small"
            style={{
              background: "#eaeaea",
              border: "none",
              borderRadius: 4,
              padding: 0,
              width: 24,
              height: 24,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
            icon={<EditOutlined style={{ color: "#bfbfbf", fontSize: 16 }} />}
            onClick={() => handleEdit(record)}
          />
          <Popconfirm
            title="确定要删除这条记录吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              size="small"
              style={{
                background: "#b6ff7a",
                border: "none",
                borderRadius: 4,
                padding: 0,
                width: 24,
                height: 24,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
              icon={<DeleteOutlined style={{ color: "#fff", fontSize: 16 }} />}
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  };

  return (
    <Card
      style={{ margin: 16 }}
      bodyStyle={{ padding: 0 }}
      title={
        <div style={{ fontWeight: "bold", fontSize: 16 }}>
          售后需求记录
          {/* <span style={{ fontWeight: "normal", fontSize: 14, marginLeft: 20 }}>
            项目编号：{projectId} 项目名称：{projectName}
          </span> */}
        </div>
      }
    >
      {/* 搜索区域 */}
      <div style={{ padding: 16, paddingBottom: 0 }}>
        <Form form={searchForm} layout="inline" style={{ marginBottom: 16 }}>
          <Form.Item name="keyword">
            <Input placeholder="搜索需求名称、备注、创建人等" style={{ width: 200 }} allowClear />
          </Form.Item>
          <Form.Item name="type">
            <Select placeholder="需求类型" style={{ width: 120 }} allowClear>
              {demandTypes.map(type => (<Option key={type.value} value={type.value}>{type.label}</Option>))}
            </Select>
          </Form.Item>
          <Form.Item name="charge">
            <Select placeholder="是否收费" style={{ width: 100 }} allowClear>
              <Option value="是">是</Option>
              <Option value="否">否</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status">
            <Select placeholder="状态" style={{ width: 100 }} allowClear>
              {statusOptions.map(status => (<Option key={status.value} value={status.value}>{status.label}</Option>))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>搜索</Button>
          </Form.Item>
          <Form.Item>
            <Button icon={<ReloadOutlined />} onClick={handleReset}>重置</Button>
          </Form.Item>
        </Form>
      </div>

      {/* 操作按钮区域 */}
      <div
        style={{
          padding: 16,
          paddingBottom: 0,
          display: "flex",
          alignItems: "center",
        }}
      >
        <Button
          type="primary"
          icon={<PlusOutlined />}
          size="small"
          style={{ marginRight: 8, background: "#1abc9c", borderColor: "#1abc9c" }}
          onClick={handleAdd}
        >
          添加
        </Button>
        <Popconfirm
          title={`确定要删除选中的 ${selectedRowKeys.length} 条记录吗？`}
          onConfirm={handleBatchDelete}
          okText="确定"
          cancelText="取消"
          disabled={selectedRowKeys.length === 0}
        >
          <Button
            type="primary"
            danger
            icon={<DeleteOutlined />}
            size="small"
            style={{ marginRight: 8 }}
            disabled={selectedRowKeys.length === 0}
          >
            批量删除 ({selectedRowKeys.length})
          </Button>
        </Popconfirm>
      </div>

      {/* 表格 */}
      <Spin spinning={loading}>
        <Table
          rowSelection={{
            type: "checkbox",
            ...rowSelection,
          }}
          columns={columns}
          dataSource={list}
          pagination={false}
          size="small"
          style={{ margin: 16 }}
          bordered
          scroll={{ x: "max-content" }}
          rowKey="id"
        />
      </Spin>

      {/* 分页 */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          padding: "0 16px 16px 16px",
        }}
      >
        <span style={{ fontSize: 12 }}>
          显示第 {list.length === 0 ? 0 : (current - 1) * pageSize + 1} 到第{" "}
          {Math.min(current * pageSize, total)} 条记录，总共{" "}
          {total} 条记录
        </span>
        <Pagination
          style={{ marginLeft: "auto" }}
          size="small"
          current={current}
          pageSize={pageSize}
          total={total}
          onChange={handlePageChange}
          showSizeChanger={false}
        />
      </div>

      {/* 添加/编辑模态框 */}
      <Modal
        title={editingRecord ? "编辑售后需求" : "添加售后需求"}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => setModalVisible(false)}
        width={600}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            charge: "否",
            status: "待处理",
            priority: "中"
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="售后需求名称"
                rules={[{ required: true, message: '请输入需求名称' }]}
              >
                <Input placeholder="请输入需求名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="type"
                label="需求类型"
                rules={[{ required: true, message: '请选择需求类型' }]}
              >
                <Select placeholder="请选择需求类型">
                  {demandTypes.map(type => (
                    <Option key={type.value} value={type.value}>{type.label}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="planHour"
                label="总计划工时"
                rules={[{ required: true, message: '请输入计划工时' }]}
              >
                <InputNumber
                  placeholder="请输入计划工时"
                  style={{ width: '100%' }}
                  min={0}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="cost"
                label="需求成本"
                rules={[{ required: true, message: '请输入需求成本' }]}
              >
                <Input placeholder="请输入需求成本" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="charge"
                label="是否收费"
                rules={[{ required: true, message: '请选择是否收费' }]}
              >
                <Select placeholder="请选择是否收费">
                  <Option value="是">是</Option>
                  <Option value="否">否</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  {statusOptions.map(status => (
                    <Option key={status.value} value={status.value}>{status.label}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="priority"
                label="优先级"
                rules={[{ required: true, message: '请选择优先级' }]}
              >
                <Select placeholder="请选择优先级">
                  {priorityOptions.map(priority => (
                    <Option key={priority.value} value={priority.value}>{priority.label}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="assignee"
                label="负责人"
              >
                <Input placeholder="请输入负责人" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="详细描述"
          >
            <TextArea
              placeholder="请输入详细描述"
              rows={4}
            />
          </Form.Item>

          <Form.Item
            name="remark"
            label="备注"
          >
            <TextArea
              placeholder="请输入备注"
              rows={3}
            />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
}